<template>
  <div class="customer-analysis-view">
    <h1>客户分析</h1>
    <div class="charts-grid">
      <div class="chart-item">
        <h3>客户类型分布</h3>
        <div class="chart-wrapper">
          <v-chart :option="customerTypeOption" autoresize />
        </div>
      </div>
      <div class="chart-item">
        <h3>客户状态分布</h3>
        <div class="chart-wrapper">
          <v-chart :option="customerStatusOption" autoresize />
        </div>
      </div>
      <div class="chart-item">
        <h3>需求类型分布</h3>
        <div class="chart-wrapper">
          <v-chart :option="demandTypeOption" autoresize />
        </div>
      </div>
      <div class="chart-item">
        <h3>需求状态分布</h3>
        <div class="chart-wrapper">
          <v-chart :option="demandStatusOption" autoresize />
        </div>
      </div>
      <div class="chart-item full-width">
        <h3>区域用户数量分布</h3>
        <div class="chart-wrapper">
          <v-chart :option="zoneUserCountOption" autoresize />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { getCustomerAnalysisData } from '@/apis/analyticsAPI'
import VChart from 'vue-echarts'
import { use, graphic } from 'echarts/core'
import {
  CanvasRenderer,
  SVGRenderer
} from 'echarts/renderers'
import {
  PieChart,
  BarChart,
  LineChart,
  RadarChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  ToolboxComponent
} from 'echarts/components'

// 注册必须的组件
use([
  CanvasRenderer,
  SVGRenderer,
  PieChart,
  BarChart,
  LineChart,
  RadarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  ToolboxComponent
])

// 数据映射
const customerTypeMap = {
  0: '居民',
  1: '商业',
  2: '工业',
  3: '农业'
}

const customerStatusMap = {
  0: '正常',
  1: '停用',
  2: '欠费'
}

const demandTypeMap = {
  0: '新装增容',
  1: '故障报修',
  2: '用电咨询'
}

const demandStatusMap = {
  0: '待处理',
  1: '已完成'
}

const urgencyLevelMap = {
  0: '一般',
  1: '紧急',
  2: '特急'
}

// 数据引用
const customerData = ref({
  customerTypeDistribution: [],
  demandTypeDistribution: [],
  demandStatusDistribution: [],
  urgencyLevelDistribution: [],
  customerStatusDistribution: [],
  zoneUserCountData: []
})

// 客户类型分布图表配置
const customerTypeOption = computed(() => {
  const pieData = customerData.value.customerTypeDistribution.map(item => ({
    name: customerTypeMap[item.type] || '未知类型',
    value: item.count
  }))
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '客户类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
})

// 客户状态分布图表配置
const customerStatusOption = computed(() => {
  const pieData = customerData.value.customerStatusDistribution.map(item => ({
    name: customerStatusMap[item.type] || '未知状态',
    value: item.count
  }))
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '客户状态',
        type: 'pie',
        radius: '60%',
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          formatter: '{b}: {c}\n({d}%)'
        },
        data: pieData
      }
    ]
  }
})

// 需求类型分布图表配置
const demandTypeOption = computed(() => {
  const barData = customerData.value.demandTypeDistribution.map(item => ({
    name: demandTypeMap[item.type] || '未知类型',
    value: item.count
  }))
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const data = params[0]
        return `${data.name}\n数量: ${data.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: barData.map(item => item.name),
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量'
      }
    ],
    series: [
      {
        name: '需求类型',
        type: 'bar',
        barWidth: '60%',
        data: barData.map(item => item.value),
        itemStyle: {
          borderRadius: [5, 5, 0, 0],
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#d4fc79' },
            { offset: 0.5, color: '#96e6a1' },
            { offset: 1, color: '#96e6a1' }
          ])
        }
      }
    ]
  }
})

// 需求状态分布图表配置
const demandStatusOption = computed(() => {
  const lineData = customerData.value.demandStatusDistribution.map(item => ({
    name: demandStatusMap[item.type] || '未知状态',
    value: item.count
  }))
  
  return {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        return `${data.name}\n数量: ${data.value}`
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%'
    },
    xAxis: [
      {
        type: 'category',
        data: lineData.map(item => item.name),
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          alignWithLabel: true,
          lineStyle: {
            color: '#ddd'
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        nameTextStyle: {
          color: '#666',
          fontSize: 12
        },
        min: 0,
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed'
          }
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      }
    ],
    series: [
      {
        name: '需求状态',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#4e72b8'
        },
        areaStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(78, 114, 184, 0.6)' },
            { offset: 0.5, color: 'rgba(78, 114, 184, 0.3)' },
            { offset: 1, color: 'rgba(78, 114, 184, 0.1)' }
          ])
        },
        itemStyle: {
          color: '#4e72b8',
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          focus: 'series'
        },
        data: lineData.map(item => item.value)
      }
    ]
  }
})

// 区域用户数量分布图表配置
const zoneUserCountOption = computed(() => {
  const barData = customerData.value.zoneUserCountData
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const data = params[0]
        return `${data.name}\n用户数量: ${data.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: barData.map(item => item.zoneName),
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          rotate: 45
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '用户数量'
      }
    ],
    series: [
      {
        name: '用户数量',
        type: 'bar',
        barWidth: '60%',
        data: barData.map(item => item.count),
        itemStyle: {
          borderRadius: [5, 5, 0, 0],
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ffecd2' },
            { offset: 0.5, color: '#fcb69f' },
            { offset: 1, color: '#fcb69f' }
          ])
        }
      }
    ]
  }
})

onMounted(async () => {
  try {
    const response = await getCustomerAnalysisData()
    customerData.value = response.data
  } catch (error) {
    console.error('获取客户分析数据失败:', error)
  }
})
</script>

<style scoped>
.customer-analysis-view {
  padding: 20px;
}

.customer-analysis-view h1 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 20px;
}

.chart-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-item.full-width {
  grid-column: 1 / -1;
}

.chart-item h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #555;
}

.chart-wrapper {
  height: 400px;
  width: 100%;
}

@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-item.full-width {
    grid-column: 1;
  }
}

@media (max-width: 768px) {
  .customer-analysis-view {
    padding: 10px;
  }
  
  .chart-wrapper {
    height: 300px;
  }
}
</style>
